package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.memberDto.DeviceDataPageReqDto;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-28
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        if(ObjectUtil.isEmpty(dto)) return new TableDataInfo();

        Page<DeviceData> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        Page<DeviceData> dataPage = page(page, Wrappers.<DeviceData>lambdaQuery()
                .like(dto.getDeviceName() != null && !dto.getDeviceName().trim().isEmpty(), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(dto.getFunctionId() != null, DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
        );
        return getTableDataInfo(page);
    }

    // 获取表格数据
    private TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备信息
     * @param iotMsgNotifyData 设备信息
     */
    @Override
    public void batchInsert(IotMsgNotifyData iotMsgNotifyData) {

        // 根据设备ID 查询是否有这个设备
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            // 结束插入
            return;
        }

        // 有这个设备 就保存数据

        // 获取服务属性
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if(CollUtil.isEmpty(properties)){
                return;
            }

            // 获取上传数据时间
            String eventTimeStr = service.getEventTime();
            LocalDateTime dateTime = LocalDateTimeUtil.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(dateTime);

            // 准备插入数据
            List<DeviceData> deviceDataList = new ArrayList<>();

            properties.forEach((key,value)->{
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId( null);
                deviceData.setCreateTime( null);
                deviceData.setFunctionId( key);
                deviceData.setDataValue( value.toString());
                deviceData.setAlarmTime( eventTime);
                deviceDataList.add(deviceData);
            });

            // 批量插入
            saveBatch(deviceDataList);

            // 批量插入数据到redis
            redisTemplate.opsForHash().put(CacheConstants.REDIS_DEVICE_DATA_KEY, iotId, JSON.toJSONString(deviceDataList));

        });


    }
}
